package com.flyim.framework.netty;

import org.springframework.stereotype.Component;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Package: com.flyim.framework.netty
 * @ClassName: ChannelManager.java
 * @Description: 维护在线用户与 Channel 的映射关系
 * @author: zhengxiaolong
 * @date: 2025/2/21 14:16
 */
@Component
public class ChannelManager {
//    维护在线用户与 Channel 的映射关系
    private static ConcurrentHashMap<String, Channel> onlineUsers = new ConcurrentHashMap<>();

    /**
     * 绑定用户与 Channel 的映射关系
     * @param userId
     * @param channel
     */
    public static void bindUser(String userId, Channel channel) {
        onlineUsers.put(userId, channel);
    }

    /**
     * 根据用户ID获取对应的Channel
     * @param userId
     * @return
     */
    public static Channel getChannel(String userId) {
        return onlineUsers.get(userId);
    }

    /**
     * 根据Channel移除对应的用户
     * @param channel
     */
    // 移除用户绑定
    public static void removeUser(Channel channel) {
        onlineUsers.entrySet().removeIf(entry -> entry.getValue() == channel);
    }

    // 根据 Channel 获取用户ID
    public static String getUserIdByChannel(Channel channel) {
        for (Map.Entry<String, Channel> entry : onlineUsers.entrySet()) {
            if (entry.getValue() == channel) {
                return entry.getKey();
            }
        }
        return null;
    }
    /**
     * 获取在线用户
     * @return
     */
    public static Set<String> getOnlineUsers() {
        return onlineUsers.keySet();
    }

    /**
     * 广播消息
     * @param jsonString
     */
    public static void broadcast(String jsonString) {
        for (Channel channel : onlineUsers.values()){
            channel.writeAndFlush(jsonString);
        }
    }
}